package com.zhengtoon.mctoon.conv.interceptor;

import com.alibaba.fastjson.JSON;
import com.bjtoon.framework.entity.ResponseResult;
import com.zhengtoon.mctoon.conv.bean.session.OrgSessionInfo;
import com.zhengtoon.mctoon.conv.exception.ConvPhotoExceptionCode;
import com.zhengtoon.mctoon.conv.service.IOrgSessionService;
import com.zhengtoon.mctoon.conv.utils.AppConstant;
import com.zhengtoon.mctoon.conv.utils.SessionUtils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截session参数并校验
 *
 * @author liuzhenhua
 * @since 2017-05-09
 */
@Component
public class SessionInterceptor implements HandlerInterceptor {

    private static Logger log = LoggerFactory.getLogger(SessionInterceptor.class);
    @Autowired
    private IOrgSessionService orgSessionService;


    @Override
    public boolean preHandle(final HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {

        res.setCharacterEncoding("utf-8");

        ResponseResult mr = new ResponseResult("");
        mr.setMeta(ConvPhotoExceptionCode.SESSION_IS_FAIL);

        try {
            String sessionId = getSessionIdFromRequest(req);

            if (StringUtils.isBlank(sessionId)) {
                mr.setMeta(ConvPhotoExceptionCode.SESSION_IS_FAIL);
                res.getWriter().write(JSON.toJSONString(mr));
                res.getWriter().flush();
                return false;
            }

            OrgSessionInfo orgSessionInfo = orgSessionService.getOrgSessionInfo(sessionId);

            if (orgSessionInfo != null) {
                handleRequest(req, orgSessionInfo);
                return true;
            }

            res.getWriter().write(JSON.toJSONString(mr));
            res.getWriter().flush();
            return false;

        } catch (Exception e) {
            log.error(e.toString() + "：" + e.getCause());
        }
        return false;
    }

    /**
     * 将session信息放入请求中
     *
     * @param req
     * @param sessionInfo
     */
    private void handleRequest(HttpServletRequest req, OrgSessionInfo sessionInfo) {
//        req.setAttribute(AppConstant.REQ_SESSION_ATTR_KEY, sessionInfo);
        SessionUtils.setSessionInfo(sessionInfo);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        SessionUtils.removeSessionInfo();
    }

    /**
     * 从请求参数中获取session token
     *
     * @param req
     * @return
     */
    private String getSessionIdFromRequest(HttpServletRequest req) {

        return req.getHeader(AppConstant.CONV_HTTP_HEADER_KEY);
    }
}
